package com.moyuxi.sound_of_the_forest.ui.pages.musicClassify

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.Divider
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.moyuxi.sound_of_the_forest.R
import com.moyuxi.sound_of_the_forest.entity.LocalMusicBean
import com.moyuxi.sound_of_the_forest.ui.compose.MusicImageCompose
import com.moyuxi.sound_of_the_forest.ui.compose.MyTopAppBarCompose
import com.moyuxi.sound_of_the_forest.ui.route.MusicClassifyRouter
import com.moyuxi.sound_of_the_forest.viewModel.MainViewModel
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun MusicClassifyScreen(
    barVisible: Boolean,
    mainVM: MainViewModel,
    titleText: String,
    openDrawer: () -> Unit,
    actionClick: () -> Unit,
    content: @Composable () -> Unit
) {
    // 底部抽屉需要的功能参数
    val state = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
    val scope = rememberCoroutineScope()
    val showSheet: () -> Unit = { scope.launch { state.show() } }

    // 播放列表需要的参数
    val bean by mainVM.playMusicBean.observeAsState(LocalMusicBean())
    val list by mainVM.playMusicList.observeAsState(mutableListOf())

    // 底部控制器参数
    val musicBean by mainVM.playMusicBean.observeAsState(LocalMusicBean())
    val isPlaying by mainVM.isPlaying.observeAsState(false)
    val progressLinear by mainVM.playingProgress.observeAsState(0.0f)
    // 底部控制器事件
    val cLast: () -> Unit = { mainVM.playLastMusic() }
    val cCurrent: () -> Unit = { mainVM.playCurrentMusic() }
    val cNext: () -> Unit = { mainVM.playNextMusic() }

    // 返回拦截 抽屉返回关闭
    BackHandler(
        enabled = state.currentValue == ModalBottomSheetValue.HalfExpanded || state.currentValue == ModalBottomSheetValue.Expanded
    ) { scope.launch { state.hide() } }

    ModalBottomSheetLayout(
        {
            PlayMusicListCompose(
                bean,
                list,
                { mainVM.playMusicInBean(it) }) { mainVM.removeSongInPlayingList(it) }
        }, sheetState = state, sheetContentColor = MaterialTheme.colorScheme.primaryContainer  // 失效
    ) {
        Column(
            modifier = Modifier.fillMaxWidth()
//                .background(Color.Transparent)
        ) {
            // 标题栏
            MyTopAppBarCompose(
                visible = barVisible,
                title = titleText,
                navClick = openDrawer,
                actionVisible = MusicClassifyRouter.MusicList.name == titleText,
                actionClick = actionClick
            )
            //中间列表内容
            Surface(modifier = Modifier.weight(1f)) { content() }
            // 底部播放控制器
            Column(modifier = Modifier
                .fillMaxWidth()
                .clickable { /*TODO 跳转至播放页面*/ }) {
                BottomPlayerControllerCompose(
                    musicBean, isPlaying, progressLinear, showSheet, cLast, cCurrent, cNext
                )
            }
        }
    }
}

/**
 * 播放列表弹出层组件
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PlayMusicListCompose(
    bean: LocalMusicBean,
    list: List<LocalMusicBean>,
    playMusicClick: (LocalMusicBean) -> Unit,
    removeOnList: (LocalMusicBean) -> Unit
) { //取消点击效果
    val interactionSource = remember { MutableInteractionSource() }
    Column(
        Modifier
            .fillMaxWidth()
            .padding(10.dp)
    ) {
        Row(
            modifier = Modifier
                .height(IntrinsicSize.Min)
                .fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            MusicImageCompose(bean.path)
            Column(
                modifier = Modifier
                    .fillMaxHeight()
                    .fillMaxWidth(),
                verticalArrangement = Arrangement.SpaceEvenly
            ) {
                Text(text = bean.name, fontSize = 20.sp, modifier = Modifier.basicMarquee())
                Text(text = bean.singer, fontSize = 15.sp, modifier = Modifier.basicMarquee())
            }
        }
        Row(
            Modifier
                .fillMaxWidth()
                .padding(5.dp), verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = list.indexOf(bean).let { if (it > -1) "${it + 1}/${list.size}" else "-/-" },
                fontSize = 15.sp,
                modifier = Modifier.weight(1f)
            )
            Text(
                text = "播放队列",
                fontSize = 20.sp,
                textAlign = TextAlign.Center,
                modifier = Modifier.weight(1f)
            )
            Text(
                text = "清除",
                fontSize = 15.sp,
                textAlign = TextAlign.Right,
                modifier = Modifier.weight(1f)
            )
        }
        Divider()
        if (list.isEmpty()) Text(text = "空空的呢，快加入一首听听吧。")
        else LazyColumn(
            contentPadding = PaddingValues(3.dp),// verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            items(list.toList()) {
                Row(modifier = Modifier
                    .fillMaxWidth()
                    .background(if (it == bean) MaterialTheme.colorScheme.secondaryContainer else Color.Transparent)
                    .clickable { playMusicClick.invoke(it) }
                    .padding(10.dp),
                    verticalAlignment = Alignment.CenterVertically) {
                    Column(modifier = Modifier.weight(1f)) {
                        Text(text = it.name, fontSize = 20.sp)
                        Text(text = it.singer, fontSize = 15.sp)
                    }
                    Image(painter = painterResource(id = R.drawable.icon_remove_36),
                        contentDescription = "移出列表",
                        contentScale = ContentScale.FillHeight,
                        modifier = Modifier.clickable(
                            interactionSource, null
                        ) { removeOnList.invoke(it) })
                }
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun BottomPlayerControllerCompose(
    musicBean: LocalMusicBean,
    isPlaying: Boolean,
    progressLinear: Float,
    showSheet: () -> Unit,
    cLast: () -> Unit,
    cCurrent: () -> Unit,
    cNext: () -> Unit
) {
    val modFMW = Modifier.fillMaxWidth()
    Column(modifier = modFMW) {
        LinearProgressIndicator(progress = progressLinear, modifier = modFMW)
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp)
                .padding(3.dp)
        ) {
            MusicImageCompose(
                modifier = Modifier
                    .size(50.dp)
                    .padding(3.dp)
                    .clip(MaterialTheme.shapes.large),
                filePath = musicBean.path,
                contentScale = ContentScale.FillHeight
            )
            // 歌曲信息
            Column(
                Modifier.weight(1f)
            ) {
                Text(musicBean.name, modifier = Modifier.basicMarquee())
                Text(musicBean.singer, modifier = Modifier.basicMarquee())
            }
            Row(
                Modifier.fillMaxHeight(), verticalAlignment = Alignment.CenterVertically, //设置垂直方向对齐
                horizontalArrangement = Arrangement.spacedBy(5.dp) //设置子项的间距
            ) {
                // 上一首按钮
                Image(painter = painterResource(id = R.drawable.icon_last),
                    contentDescription = "上一首",
                    modifier = Modifier
                        .clickable { cLast.invoke() }
                        .size(30.dp))
                // 播放暂停按钮
                Image(painter = painterResource(if (isPlaying) R.drawable.icon_pause else R.drawable.icon_play),
                    contentDescription = "播放或者暂停",
                    modifier = Modifier
                        .clickable { cCurrent.invoke() }
                        .size(35.dp))
                // 下一首按钮
                Image(painter = painterResource(id = R.drawable.icon_next),
                    contentDescription = "下一首",
                    modifier = Modifier
                        .clickable { cNext.invoke() }
                        .size(30.dp))
                Image(painter = painterResource(id = R.drawable.icon_line),
                    contentDescription = "播放列表",
                    modifier = Modifier
                        .size(30.dp)
                        .clickable { showSheet.invoke() })
            }
        }
    }
}